package com.cbs.android.module.user.network;

import com.cbs.android.component.applicationutils.network.CBSRequest;
import com.cbs.android.component.log.L;
import com.cbs.android.module.user.user.UserModule;


/**
 * Created by broche on 11/19/15.
 */
public class CBSUserRequest extends CBSRequest {
    public static final String CBSAUTHORIZATION = "CBSAUTHORIZATION";
    public static final String CBSUSERID = "USER-ID";
    private static final String TAG = CBSUserRequest.class.getName();
    public static final String Mark = "{uid}";

    public CBSUserRequest(String url) {
        super(url);
        if (UserModule.getUser() != null) {
            header(CBSAUTHORIZATION, UserModule.getUser().getToken());
            header(CBSUSERID, String.valueOf(UserModule.getUser().getId()));
        } else {
            L.e(TAG, "user is null");
        }
    }

    public CBSUserRequest(CBSUserRequest request) {
        super(request);
        if (UserModule.getUser() != null) {
            header(CBSAUTHORIZATION, UserModule.getUser().getToken());
            header(CBSUSERID, String.valueOf(UserModule.getUser().getId()));
        } else {
            L.e(TAG, "user is null");
        }
    }

    public CBSUserRequest setResponseHandler(UserResponseHandler handler) {
        super.setResponseHandler(handler);
        return this;
    }

    @Override
    public okhttp3.Request build() {
        if (url.contains(Mark)) {
            if (UserModule.getUser() != null) {
                url = url.replace(Mark, UserModule.getUser().getId() + "");
            } else {
                if (getResponseHandler() != null && UserResponseHandler.class.isAssignableFrom(getResponseHandler().getClass())) {
                    ((UserResponseHandler) getResponseHandler()).onUnAuthorized(this);
                }
                return null;
            }
        }
        return super.build();
    }

    @Override
    protected CBSUserRequest clone() throws CloneNotSupportedException {
        CBSUserRequest request = new CBSUserRequest(this);
        return request;
    }
}
